package org.theSeed.springBase.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;

import java.util.Collections;
import java.util.List;

/**
 * spring配置类工具
 */
public class PropUtil {
    private static Binder binder;

    /**
     * 获取绑定工具
     * @return
     */
    private synchronized static Binder getBinder(){
        if (ObjectUtil.isNull(binder)){
            Environment env = SpringUtil.getBean(Environment.class);
            binder = Binder.get(env);
        }
        return binder;
    }

    /**
     * 获取配置类
     * @param keyPrefix
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T getConfigObj(String keyPrefix, Class<T> clazz){
        return (T)(getBinder().bind(keyPrefix,clazz)).orElse(null);
    }

    /**
     * 获取配置类数组
     * @param keyPrefix
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> List<T> getConfigObjList(String keyPrefix, Class<T> clazz){
        return (List<T>)(getBinder().bind("myapp.servers", Bindable.listOf(String.class))
                .orElse(Collections.emptyList()));
    }
}